package common.messages;

import client.TextMessage;

public class KVMessageImpl implements KVMessage {	
	
	private String key;
	private String value;
	private KVMessage.StatusType status ;
	
	public KVMessageImpl(String key, String value, KVMessage.StatusType status){
		this.key = key.trim();
		this.value = value.trim();
		this.status = status;				
	}
	
	public KVMessageImpl(byte[] response){
		boolean parseStatus = parseBytes(response);
		if(!parseStatus){
			key = "ERROR";
			value = "ERROR";
			status = KVMessage.StatusType.UNKNOWN;
		}		
	}
	
	private boolean parseBytes(byte[] responseBytes){
		TextMessage message = new TextMessage(responseBytes);
		String data = message.getMsg();
		String[] tokens = data.split(SEPARATOR);
		if(tokens.length < 2)
			return false;
		if(tokens.length > 3)
			return false;
		String status = tokens[0];
		String key = tokens[1];
		String value = "";
		if(tokens.length == 2)
			value = tokens[1];
		else
			value = tokens[2];
		
		this.status = KVMessage.StatusType.getStatus(status);
		this.key = key.trim();
		this.value = value.trim();
		
		return true;
	}
	
	@Override
	public String getKey() {
		return key;
	}

	@Override
	public String getValue() {
		return value;
	}

	@Override
	public StatusType getStatus() {
		return status;
	}

	public String toString(){
		String msg = "";
		msg += status.name() + SEPARATOR + key + SEPARATOR + value;
		return msg;
	}
	
	public byte[] toBytes(){
		String msg = this.toString();
		TextMessage bytes = new TextMessage(msg);
		return bytes.getMsgBytes();
	}
	
}
